package com.burgeon.backend.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.burgeon.backend.Rest.Tool.GetVIPType;
import com.burgeon.backend.Rest.User.*;
import com.burgeon.backend.Rest.User.item.FindItemList;
import com.burgeon.backend.Rest.User.util.DeleteVip;
import com.burgeon.backend.Rest.User.vipType.FindEmpNameByNO;
import com.burgeon.backend.Rest.coupon.util.CreateIntegral;
import com.burgeon.backend.Rest.store.GetStoreName;
import com.burgeon.backend.SHOPBACKEND.entity.Employee;
import com.burgeon.backend.Util.menu.WeixinUtil;
import com.burgeon.backend.entity.*;
import com.burgeon.backend.mappers.*;
import com.burgeon.backend.service.CouponService;
import com.burgeon.backend.service.MessageTemplateService;
import com.burgeon.backend.service.UserService;
import com.burgeon.backend.service.WechatService;
import com.burgeon.backend.service.ex.ErrorDataException;
import com.burgeon.backend.service.ex.GetUserDataException;
import com.burgeon.backend.service.ex.InsertException;
import com.burgeon.backend.service.ex.UserNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    private final static Log logger = LogFactory.getLog(UserService.class);

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FieldsMapper fieldsMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private TemplateMapper templateMapper;
    @Autowired
    private CouponService couponService;
    @Autowired
    private MessageTemplateService messageTemplateService;
    @Autowired
    private WechatService wechatService;

    @Override
    public ArrayList<RetailRecordItem> getVipRetailItem(String id, String token) {
        Info info = GetInfoByToken(token);
        GetRetailItem getRetailItem = new GetRetailItem(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getRetailItem.getData(id);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());
        }
        return null;
    }

    @Override
    public ArrayList<RetailRecord> getVipRetail(String phone, String token) {
        Info info = GetInfoByToken(token);
        GetRetailByVip getRetailByVip = new GetRetailByVip(info.getUrl(), info.getAccount(), info.getPassword());
        try {
           return getRetailByVip.getData(phone);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());
        }
        return null;
    }

    @Override
    public ArrayList<RechargeItem> getVipRechargeItem(String phone, String token) {
        Info info = GetInfoByToken(token);
        FindItemList findItemList = new FindItemList(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return findItemList.getData(phone);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            System.err.println(e.getMessage());
            return null;
        }
    }

    @Override
    public void ModVipData(String id, User user, String account) throws ErrorDataException {
        Info info = GetInfo(account);
        ModVipDataBos modVipDataBos = new ModVipDataBos(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            modVipDataBos.getData(id, user);
        } catch (Exception e) {
            logger.error(e.getStackTrace());
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public User GetModVipData(String id, String account) {
        Info info = GetInfo(account);
        GETUserByID getUserByID = new GETUserByID(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            return getUserByID.getData(id);
        } catch (Exception e) {
            e.getStackTrace();
            return null;
        }

    }

    /**
     * 获取卡类型
     * @param account
     * @return
     */
    @Override
    public ArrayList<String> GetVipType(String account) {
        Info info = GetInfo(account);
        GetVIPType getVipType = new GetVIPType(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            return getVipType.getData();
        } catch (Exception e) {

            return null;
        }
    }

    @Override
    public void DelVipWX(String code, String account) throws ErrorDataException {

            userMapper.delUserData(code,account);

    }

    @Override
    public void DelVip(String id,String code, String account) throws ErrorDataException {
        Info info = GetInfo(account);
        DeleteVip deleteVip = new DeleteVip(info.getUrl(), info.getAccount(), info.getPassword());
        try {
            deleteVip.getData(id);
            userMapper.delUserData(code,account);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public HashMap GetPOSData(String account, String start) throws GetUserDataException {
        Info info = GetInfo(account);
        //从bos获取user数据
        GetUserALL getUserALL = new GetUserALL(info.getUrl(), info.getAccount(), info.getPassword());
        HashMap data;
        try {
            data = getUserALL.getData(Integer.valueOf(start));
            ArrayList<User> list = (ArrayList<User>) data.get("data");

            for (User user : list) {
                try {
                    user.setImg(userMapper.FindUserDataByPhone(user.getPhone(), account).getImg());
                } catch (Exception e) {
                    user.setImg("images/1.png");
                }
            }
            data.put("data", list);
        } catch (Exception e) {
            logger.error("获取用户列表数据错误" + e.getMessage() + Arrays.toString(e.getStackTrace()));
            throw new GetUserDataException("获取数据错误");
        }
        return data;
    }

    @Override
    public HashMap FindPOSUserData(String account, String start, String message) throws GetUserDataException {
        Info info = GetInfo(account);
        FindUserData findUserData = new FindUserData(info.getUrl(), info.getAccount(), info.getPassword());
        HashMap data;
        try {
            data = findUserData.getData(Integer.valueOf(start), message);
        } catch (Exception e) {

            throw new GetUserDataException("获取数据错误");
        }
        return data;
    }

    @Override
    public HashMap GetWXData(String account, String start) throws GetUserDataException {
        HashMap data = new HashMap();
        List<User> list = userMapper.GetWXUserData(Integer.valueOf(start)*20, account);
        Info info = GetInfo(account);
        List<User> usersList = new ArrayList<>();
        for (User user:list) {
            FindEmpNameByNO findEmpNameByNO = new FindEmpNameByNO(info.getUrl(),info.getAccount(),info.getPassword());
            try {
                user.setEmp( findEmpNameByNO.getData(user.getEmp()));
                usersList.add(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String count = userMapper.GetUserCountList(account);
        data.put("count", count);
        data.put("data", usersList);
        return data;
    }

    @Override
    public HashMap FindWXUserData(String account, String start, String message) throws GetUserDataException {
        HashMap data = new HashMap();
        List list = userMapper.FindWXUserData(Integer.valueOf(start), account, message);
        String count = userMapper.FindUserCount(account, message);
        data.put("count", count);
        data.put("data", list);
        return data;
    }

    @Override
    public void RegisterUser(User user) throws InsertException {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(now);
        user.setAccount(TokenGetAccount(user.getToken()));
        user.setCreateTime(dateString);
        user.setFinish("Y");
        Integer row = userMapper.Register(user);
        if (row != 1) {
            throw new InsertException("注册数据异常");
        }
        //系统中注册
        user.setType(fieldsMapper.GetDataToken(user.getToken()).getType());
        user.setCustomer(storeMapper.FindStoreData(user.getStore(), user.getToken()).getCustomerup());
        user.setStorejh(user.getStore());
        Info info = GetInfoByToken(user.getToken());
        CreateUser createUser = new CreateUser(info.getUrl(), info.getAccount(), info.getPassword());

        try {
            createUser.getData(user);
        } catch (Exception e) {
            logger.error("注册出错" + e.getMessage());
            throw new InsertException("注册出错，稍后重试");
        }

        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ignored) {
            }
            //发券  发积分  发消息
            TemplateSwitch templateSwitch = templateMapper.FindTemplateSwitch(user.getAccount());
            if ("Y".equals(templateSwitch.getSwitch1())) {
                //发券
                System.err.println(user);
                couponService.addCoupon(templateSwitch.getValue1(), user.getPhone(), user.getAccount());
            }
            if ("Y".equals(templateSwitch.getSwitch2())) {
                CreateIntegral createIntegral = new CreateIntegral(info.getUrl(), info.getAccount(), info.getPassword());
                try {
                    Thread.sleep(1000);
                    createIntegral.getData(user.getPhone(), "-"+templateSwitch.getValue2());
                    messageTemplateService.SendMessageForNewUser(user.getToken(), user.getOpenid(), user.getPhone(), "-" + templateSwitch.getValue2(), user.getName());
                } catch (Exception e) {
                    logger.error("新会员注册积分调整错误" + Arrays.toString(e.getStackTrace()) + e.getMessage());

                }
            }
        });
        thread.start();
    }

    @Override
    public User FindUser(String openid, String token) throws UserNotFoundException {
        Info info = GetInfoByToken(token);
        GETUserByOpenid getUserByOpenid = new GETUserByOpenid(info.getUrl(), info.getAccount(), info.getPassword());
        User data;
        try {
            data = getUserByOpenid.getData(openid);
            User mydata = userMapper.FindUser(openid, token);
            data.setImg(mydata.getImg());
        } catch (Exception e) {
            throw new UserNotFoundException("数据错误");
        }
        return data;
    }

    /**
     * 累计关注会员数
     * @param account
     * @return
     */
    @Override
    public String getWxVipCount(String account) {
        String accessToken = wechatService.GetAccesTokenByAccount(account);
        String action = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        //发送给微信
        JSONObject jsonObject = WeixinUtil.httpRequest(action,"GET","");
        String count=jsonObject.getString("total");

        return count;
    }

    /**
     * 获取绑定/注册
     * @param account
     * @param source
     * @return
     */
    @Override
    public String getUserCount(String account, String source) {
        String userCount = userMapper.getUserCount(account,source);
        return userCount;
    }

    /**
     * 获取购买的会员数
     * @param account
     * @return
     */
    @Override
    public String getPayUserCount(String account) {
        String payUserCount = userMapper.getPayUserCount(account);
        return payUserCount;
    }

    /**
     * 激活erp会员卡数
     * @param account
     * @return
     */
    @Override
    public String getJHUserCount(String account) {
        String jUserCount = userMapper.getJHUserCount(account);
        return jUserCount;
    }

    @Override
    public HashMap getVariousUser(String account) {
        HashMap map = new HashMap();
        //关注公众号的总数
        String accessToken = wechatService.GetAccesTokenByAccount(account);
        String action = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        JSONObject jsonObject = WeixinUtil.httpRequest(action,"GET","");
        String count=jsonObject.getString("total");

        //绑定
        String userCount = userMapper.getUserCount(account,"B");
        //注册
        String userZCCount = userMapper.getUserCount(account,"Z");
        //购买
        String payUserCount = userMapper.getPayUserCount(account);
        //激活
        String jUserCount = userMapper.getJHUserCount(account);
        map.put("WxCount",count);
        map.put("BangCount",userCount);
        map.put("ZhuCount",userZCCount);
        map.put("PayCount",payUserCount);
        map.put("JHuoCount",jUserCount);
        Info info = GetInfo(account);
        GetUserCount getUserCount = new GetUserCount(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            String posCount = getUserCount.getData(0);
            map.put("PosCount",posCount);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        return map;
    }

    /**
     * 获取店铺
     * @param account
     * @return
     */
    @Override
    public ArrayList<CardStore> GetVipStore(String account) {
        Info info = GetInfo(account);
        GetStoreName getStoreName = new GetStoreName(info.getUrl(),info.getAccount(),info.getPassword());
        try {
           return getStoreName.getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据店铺员工
     * @param storeId
     * @param account
     * @return
     */
    @Override
    public ArrayList<Employee> GetEmpByStoreId(String storeId, String account) {
        Info info = GetInfo(account);
        FindEmpByStoreId findEmpByStoreId = new FindEmpByStoreId(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            return findEmpByStoreId.getData(storeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据筛选条件查询用户
     * @param account
     * @param vipType
     * @param store
     * @param storejh
     * @param birthday
     * @param cStartTime
     * @param cEndTime
     * @param page
     * @return
     */
    @Override
    public HashMap FindUserBys(String account, String vipType, String store, String empNO,
                                       String storejh, String birthday, String cStartTime,
                                       String cEndTime, int page) {
        HashMap data = new HashMap();
        Info info = GetInfo(account);

        ArrayList<User> usersList = new ArrayList<>();
        UserVo userVo = new UserVo();

        int start = (page-1)*20;
        ArrayList<User> users = userMapper.FindUserBys(account,vipType,store,empNO,storejh,birthday,
                cStartTime,cEndTime,start);

        if (users.size()>0){
            for (User user:users) {
                FindEmpNameByNO findEmpNameByNO = new FindEmpNameByNO(info.getUrl(),info.getAccount(),info.getPassword());
                String empName= null;
                try {
                    empName = findEmpNameByNO.getData(empNO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                user.setEmp(empName);
                usersList.add(user);
            }
        }

        String count = userMapper.FindUserCountBys(account,vipType,store,empNO,storejh,birthday,
                cStartTime,cEndTime);

        data.put("data", usersList);
        data.put("count", count);

        return data;
    }

    @Override
    public String findPhone(String uid, String token) {
        return userMapper.findPhone(uid,token);
    }


    private Info GetInfo(String account) {
        return accountMapper.GetAccData(account);
    }

    private String TokenGetAccount(String token) {
        return accountMapper.GetAccountForToken(token);
    }

    private Info GetInfoByToken(String token) {
        return accountMapper.GetTokenData(token);
    }

    public static void main(String[] args) {
        String a = "8J+Zgw==";
        //进行解码
        a = new String(Base64.decodeBase64(a), StandardCharsets.UTF_8);
        System.err.println(a);
    }
}
